package com.baselibrary.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.text.*
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.StyleSpan
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import com.baselibrary.R
import com.baselibrary.extension.checkNotNull

@SuppressLint("CustomViewStyleable")
class CommonlyExpandTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
    private val DEFAULT_OPEN_SUFFIX = "...展开"
    private val DEFAULT_CLOSE_SUFFIX = "   收起"
    var collapsed = true
        set(value) {
            if (field != value) {
                field = value
                requestLayout()
            }
        }

    private var collapsedMaxLine = 0

    private var content: String = ""

    private var hasMore = false

    private var collapsedColor = Color.parseColor("#FFFFFF")

    private var collapsedUnderLine = false

    private  var clickExpandListener :ClickExpandListener?=null
    init {
        context.obtainStyledAttributes(attrs, R.styleable.ExpandTextView).apply {
            collapsed = getBoolean(R.styleable.ExpandTextView_collapsed, true)
            collapsedMaxLine = getInt(R.styleable.ExpandTextView_collapsedMaxLine, 3)
            collapsedColor = getColor(R.styleable.ExpandTextView_collapsedColor, Color.WHITE)
            collapsedUnderLine = getBoolean(R.styleable.ExpandTextView_collapsedUnderLine, false)
            recycle()
        }

        movementMethod = LinkMovementMethod.getInstance()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (!TextUtils.isEmpty(content)) {
            if (layout != null) {
                if (layout.lineCount > collapsedMaxLine) {
                    hasMore = true
                }

                if (collapsed) {
                    if (layout.lineCount > collapsedMaxLine) {
                        maxLines = collapsedMaxLine
                        val endIndex = layout.getLineEnd(collapsedMaxLine - 1)
                        super.setText(getCollapsedContent(endIndex))
                    }
                } else {
                    if (hasMore) {
                        maxLines = Int.MAX_VALUE
                        super.setText(getAllContent())
                        hasMore = false
                    }
                }
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    fun setText(content: String) {
        this.content = content
        super.setText(content)
        maxLines = Int.MAX_VALUE
        hasMore = false
    }

    fun toggleCollapsed() {
        collapsed = !collapsed
    }

    private fun getAllContent(): SpannableStringBuilder {
        val stowSpannable = SpannableStringBuilder(content)
        return stowSpannable.apply {
            append(DEFAULT_CLOSE_SUFFIX)
            setSpan(ClickableColorSpan(collapsedColor, collapsedUnderLine) {
                collapsed = !collapsed
            }, length - DEFAULT_CLOSE_SUFFIX.length, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            setSpan(StyleSpan(Typeface.BOLD), length - 5, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        }
    }
    fun setListener(clickExpandListener: ClickExpandListener){
        this.clickExpandListener = clickExpandListener
    }


    private fun getCollapsedContent(endIndex: Int): SpannableStringBuilder {
        if (endIndex >= 3) {
            val openSpannable = SpannableStringBuilder(content.substring(0, endIndex - 3))
            return openSpannable.apply {
                append(DEFAULT_OPEN_SUFFIX).setSpan(
                    ClickableColorSpan(
                        collapsedColor,
                        collapsedUnderLine
                    ) {
                        collapsed = !collapsed
                        if (clickExpandListener.checkNotNull()){
                            clickExpandListener?.click()
                        }
                    },
                    length - DEFAULT_OPEN_SUFFIX.length,
                    length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                setSpan(
                    StyleSpan(Typeface.BOLD),
                    length - DEFAULT_OPEN_SUFFIX.length,
                    length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        } else {
            return SpannableStringBuilder(content)
        }
    }


    class ClickableColorSpan(
        private val color: Int,
        private val underLine: Boolean,
        private val click: () -> Unit
    ) : ClickableSpan() {

        override fun updateDrawState(ds: TextPaint) {
            super.updateDrawState(ds)
            ds.color = color
            ds.isUnderlineText = underLine
        }

        override fun onClick(widget: View) {
            click.invoke()
        }
    }

}
interface ClickExpandListener{
    fun click()
}
